package com.origin.src.aspect;

import org.springframework.aop.TargetSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

@Component
public class TargetSourceBean implements TargetSource, BeanFactoryAware {

    ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    @Bean(name = "targetBean0")
    @Primary
    public TargetBean bean0() {
        return new TargetBean("TargetBean0");
    }

    @Bean(name = "targetBean1")
//    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    public TargetBean bean1() {
        return new TargetBean("TargetBean1");
    }


    @Override
    public Class<?> getTargetClass() {
        return TargetBean.class;
    }

    @Override
    public boolean isStatic() {
        return false;
    }

    @Override
    public Object getTarget() throws Exception {
        int i = threadLocal.get();
        return beanFactory.getBean("targetBean" + i);
    }

    @Override
    public void releaseTarget(Object target) throws Exception {

    }

    BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
